//
//  MusicPlayerVC.m
//  echo
//
//  Created by dllo on 16/2/29.
//  Copyright © 2016年 Danny. All rights reserved.
//

#define WIDTH [UIScreen mainScreen].bounds.size.width / 414
#define HEIGHT [UIScreen mainScreen].bounds.size.height / 736

#import "MusicPlayerVC.h"
#import <AVFoundation/AVFoundation.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import "ModelForRecommendTableViewCell.h"
#import "ModelForMusicPlayer.h"
#import "ModelForHome.h"
#import "ModelForHotVCTableViewCell.h"
#import <DKNightVersion/DKNightVersion.h>
#import "ModelForExploreTableViewCell.h"
#import "ModelForSearch.h"
#import "ModelForHotVCTableViewCellSectionOneAndTwo.h"

@interface MusicPlayerVC ()
@property (nonatomic, retain)UIView *backView;
@property (nonatomic, retain)UIView *progressView;
@property (nonatomic, retain)AVPlayerItem *playItem;
@property (nonatomic, retain)AVPlayerLayer *playLayer;
@property (nonatomic, retain)AVPlayer *player;
@property (nonatomic, retain)UIButton *button;
@property (nonatomic, retain)UISlider *slider;
@property (nonatomic, retain)UILabel *labelForTime;
@property (nonatomic, assign)CGFloat videoTime;
@property (nonatomic, retain)UIVisualEffectView *visualView;
@property (nonatomic, retain)UIButton *buttonForBack;
@property (nonatomic, assign)BOOL isPlay;
@property (nonatomic, assign)BOOL isHidden;
@property (nonatomic, assign)BOOL isRotation;
@property (nonatomic, retain)id observerForMusic;
@property (nonatomic, retain)ModelForMusicPlayer *modelForData;
@end

@implementation MusicPlayerVC

- (void)dealloc{
    [_backView release];
    [_progressView release];
    [_playItem release];
    [_playLayer release];
    [_player release];
    [_button release];
    [_slider release];
    [_labelForTime release];
    [_visualView release];
    [_buttonForBack release];
    [_modelForData release];
    [_imageForBack release];
    [_labelForName release];
    [_imageForMusic release];
#pragma ** retain id类型是否dealloc
//    [_observerForMusic release];
    [_urlForMusic release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.isPlay = YES;
    self.isHidden = NO;
    self.isRotation = NO;
    [self createViews];
    [self createVideoPlayer];
    [self settingUpSlider];
}

- (void)createViews{
    self.navigationController.navigationBarHidden = YES;
    self.backView = [[UIView alloc]initWithFrame:self.view.frame];
    self.backView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.backView];
    [self.backView release];
    
    self.imageForBack = [[UIImageView alloc]initWithFrame:self.view.frame];
    [self.imageForBack sd_setImageWithURL:[NSURL URLWithString:self.modelForData.imageForBack]];
    [self.backView addSubview:self.imageForBack];
    self.imageForBack.userInteractionEnabled = YES;
    [self.imageForBack release];
    
    UIBlurEffect *blur = [UIBlurEffect effectWithStyle:1];
    self.visualView = [[UIVisualEffectView alloc]initWithEffect:blur];
    
    [self.imageForBack addSubview:self.visualView];
    
    self.visualView.frame = self.view.frame;
    self.visualView.alpha = 0.8;
    self.visualView.userInteractionEnabled = YES;
    [_visualView release];
    
    self.labelForName = [[UILabel alloc]initWithFrame:CGRectMake(50 * WIDTH, 140 * HEIGHT + self.view.frame.size.width - 95 * WIDTH + 30 * HEIGHT, self.view.frame.size.width - 100 * WIDTH, 55 * HEIGHT)];
    self.labelForName.text = self.modelForData.labelForName;
    self.labelForName.backgroundColor = [UIColor colorWithRed:232/255.f green:76/255.f blue:84/255.f alpha:1];
    self.labelForName.layer.cornerRadius = 12.5 * HEIGHT;
    self.labelForName.layer.masksToBounds = YES;
    self.labelForName.textAlignment = 1;
    self.labelForName.numberOfLines = 0;
    self.labelForName.font = [UIFont fontWithName:@"ArialUnicodeMS" size:17.0];
    [self.visualView addSubview:self.labelForName];
    [self.labelForName release];
    
    self.progressView = [[UIView alloc]initWithFrame:CGRectMake(0, 150 * HEIGHT + self.view.frame.size.width - 90 * WIDTH + 8 * HEIGHT + 32 * HEIGHT + 76 * HEIGHT, self.view.frame.size.width, 40 * HEIGHT)];
    [self.visualView addSubview:self.progressView];

    [self.progressView release];
    
    self.button = [UIButton buttonWithType:UIButtonTypeCustom];
    self.button.frame = CGRectMake(5 * WIDTH, 0, 40 * WIDTH, 40 * WIDTH);
    [self.progressView addSubview:self.button];
    [self.button release];
    [self.button setImage:[UIImage imageNamed:@"iconfont-zanting"] forState:UIControlStateNormal];
    [self.button addTarget:self action:@selector(handleButton:) forControlEvents:UIControlEventTouchUpInside];
    
    self.slider = [[UISlider alloc]initWithFrame:CGRectMake(5 * WIDTH + 40 * WIDTH + 5 * WIDTH, 0, 245 * WIDTH, 40 * HEIGHT)];
    [self.progressView addSubview:self.slider];
    [self.slider addTarget:self action:@selector(handleSlider:) forControlEvents:UIControlEventValueChanged];
    
    self.labelForTime = [[UILabel alloc]initWithFrame:CGRectMake(5 * WIDTH + 40 * WIDTH + 5 * WIDTH + 250 * WIDTH + 5 * WIDTH, 0, 110 * WIDTH, 40 * HEIGHT)];
    [self.progressView addSubview:self.labelForTime];
    [self.labelForTime release];
    
    self.buttonForBack = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonForBack.frame = CGRectMake(7 * WIDTH, 30 * HEIGHT, 40 * WIDTH, 35 * HEIGHT);
    [self.backView addSubview:self.buttonForBack];
    [self.buttonForBack setImage:[UIImage imageNamed:@"iconfont-fanhui"] forState:UIControlStateNormal];
    self.navigationItem.hidesBackButton = YES;
    [self.buttonForBack addTarget:self action:@selector(handleBackForMusic) forControlEvents:UIControlEventTouchUpInside];
    
    [self createImageViewForMusic];
    
}

- (void)handleBackForMusic{
    [self.player pause];
    [self.navigationController popViewControllerAnimated:YES];
    self.navigationItem.hidesBackButton = NO;
    self.buttonForBack.frame = CGRectMake(0, 0, 0, 0);
    self.tabBarController.tabBar.hidden = NO;
}

- (void)createImageViewForMusic{
    self.imageForMusic = [[UIImageView alloc]initWithFrame:CGRectMake(45 * WIDTH, 120 * HEIGHT, self.view.frame.size.width - 90 * WIDTH, self.view.frame.size.width - 90 * WIDTH)];
    [self.visualView addSubview:self.imageForMusic];
    [self.imageForMusic release];
    
    [self.imageForMusic sd_setImageWithURL:[NSURL URLWithString:self.modelForData.imageForMusic]];
//    self.imageForMusic.backgroundColor = [UIColor cyanColor];
    self.imageForMusic.layer.cornerRadius = (self.view.frame.size.width - 90 * WIDTH) / 2;
    self.imageForMusic.layer.masksToBounds = YES;
    self.imageForMusic.layer.borderWidth = 3 * WIDTH;
    self.imageForMusic.layer.borderColor = [UIColor greenColor].CGColor;
    self.imageForMusic.userInteractionEnabled = YES;
    
    CABasicAnimation *basicAni = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    basicAni.fromValue = [NSNumber numberWithInt:0];
    basicAni.toValue = [NSNumber numberWithInt:M_PI * 2];
    basicAni.duration = 10;
    basicAni.repeatCount = NSIntegerMax;
    basicAni.autoreverses = NO;
    basicAni.cumulative = YES;
    
    [self.imageForMusic.layer addAnimation:basicAni forKey:@"basicAnimation"];
    
}

- (void)createVideoPlayer{

    NSString *url = [NSString stringWithString:self.modelForData.urlForMusic];
    
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSURL *urlOfVideo = [NSURL URLWithString:url];
    
    self.playItem = [[AVPlayerItem alloc]initWithURL:urlOfVideo];
    self.player = [AVPlayer playerWithPlayerItem:self.playItem];
    [self.player replaceCurrentItemWithPlayerItem:self.playItem];
    [self.playItem release];
    
    [self.player play];
}

- (void)settingUpSlider{
    
    __block MusicPlayerVC *vc = self;
    self.observerForMusic =  [vc.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        CGFloat duration = CMTimeGetSeconds(self.playItem.duration);
        CGFloat current = CMTimeGetSeconds(self.playItem.currentTime);
        
        NSString *totalTime = [NSString stringWithFormat:@"%.2d:%.2d", (int)duration/60, (int)duration%60];
        NSString *currentTime = [NSString stringWithFormat:@"%.2d:%.2d", (int)current/60, (int)current%60];
        
        NSString *timeOfLabel = [NSString stringWithFormat:@"%@/%@", currentTime,totalTime];
        self.labelForTime.text = timeOfLabel;
        if ([UIScreen mainScreen].bounds.size.height == 480) {
            self.labelForTime.font = [UIFont fontWithName:@"Arial" size:15];
        }else if ([UIScreen mainScreen].bounds.size.height == 568){
            self.labelForTime.font = [UIFont fontWithName:@"Arial" size:16];
        }else{
            self.labelForTime.font = [UIFont fontWithName:@"Arial" size:17];
        }
        
        self.slider.value = current / duration;
        
        self.videoTime = duration;
    }];
}

- (void)handleButton:(UIButton *)button{
    if (self.isPlay == YES) {
        
        [self.player pause];
        
        [self.button setImage:[UIImage imageNamed:@"iconfont-bofang"] forState:UIControlStateNormal];
        CFTimeInterval stopTime = [self.imageForMusic.layer convertTime:CACurrentMediaTime() fromLayer:nil];
        self.imageForMusic.layer.speed = 0;
        self.imageForMusic.layer.timeOffset = stopTime;
        
    }else{
        
        [self.player play];
        
        [self.button setImage:[UIImage imageNamed:@"iconfont-zanting"] forState:UIControlStateNormal];
        
        CFTimeInterval stopTime = self.imageForMusic.layer.timeOffset;
        self.imageForMusic.layer.speed = 1.0;
        self.imageForMusic.layer.timeOffset = 0;
        self.imageForMusic.layer.beginTime = 0;
        self.imageForMusic.layer.beginTime = [self.imageForMusic.layer convertTime:CACurrentMediaTime() fromLayer:nil] - stopTime;
        
    };
    self.isPlay = !self.isPlay;
}

- (void)handleSlider:(UISlider *)slider{
    if (self.playItem.status == AVPlayerItemStatusReadyToPlay) {

        double currentTime = self.videoTime * self.slider.value;
        CMTime toTime = CMTimeMake(currentTime, 1);
        [self.player seekToTime:toTime completionHandler:^(BOOL finished) {
            [self.player play];
            [self.button setImage:[UIImage imageNamed:@"iconfont-zanting"] forState:UIControlStateNormal];
            self.isPlay = YES;
            self.imageForMusic.layer.speed = 1.0;
        }];
    }else {

        return;
    }
}

- (void)passModelForRecommendTableViewCell:(ModelForRecommendTableViewCell *)model{
    self.modelForData = [[ModelForMusicPlayer alloc]init];
    self.modelForData.imageForBack = model.pic_750;
    self.modelForData.imageForMusic = model.pic_750;
    self.modelForData.labelForName = model.name;
    self.modelForData.urlForMusic = model.source;
}

- (void)passModelForHome:(ModelForHome *)model{
    self.modelForData = [[ModelForMusicPlayer alloc]init];
    self.modelForData.urlForMusic = model.source;
    self.modelForData.imageForMusic = model.pic_1080;
    self.modelForData.imageForBack = model.pic_1080;
    self.modelForData.labelForName = model.name;
}

- (void)passModelModelForHotVC:(ModelForHotVCTableViewCell *)model{
    self.modelForData = [[ModelForMusicPlayer alloc]init];
    self.modelForData.urlForMusic = model.source;
    self.modelForData.imageForBack = model.pic_750;
    self.modelForData.imageForMusic = model.pic_750;
    self.modelForData.labelForName = model.name;
}

- (void)passModelModelForSearchVC:(ModelForSearch *)model{
    self.modelForData = [[ModelForMusicPlayer alloc]init];
    self.modelForData.urlForMusic = model.source;
    self.modelForData.imageForBack = model.pic;
    self.modelForData.imageForMusic = model.pic;
    self.modelForData.labelForName = model.name;
}

- (void)passModelModelForHairVC{
    self.modelForData = [[ModelForMusicPlayer alloc]init];
    self.modelForData.urlForMusic = @"http://7fvgtj.com2.z0.glb.qiniucdn.com/264868d085e25b23b00d3f27aa025af6";
    self.modelForData.imageForBack = @"http://echo-image.qiniucdn.com/Fu63In1bW8xbApr8Dg_92sB3KgAX";
    self.modelForData.imageForMusic = @"http://echo-image.qiniucdn.com/Fu63In1bW8xbApr8Dg_92sB3KgAX";
    self.modelForData.labelForName = @"戴耳机！超逼真3D虚拟理发店，身临其境的奇妙声音体验";
}

- (void)passModelForHotVCTableViewCellSectionOneAndTwo:(ModelForHotVCTableViewCellSectionOneAndTwo *)model{
    self.modelForData = [[ModelForMusicPlayer alloc]init];
    self.modelForData.urlForMusic = model.source;
    self.modelForData.imageForBack = model.pic;
    self.modelForData.imageForMusic = model.pic;
    self.modelForData.labelForName = model.name;
}

- (void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = YES;
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"夜间模式"]) {
        
        [DKNightVersionManager nightFalling];
        
    } else {
        
        [DKNightVersionManager dawnComing];
    }
    self.backView.dk_backgroundColorPicker = DKColorWithColors([UIColor whiteColor], [UIColor colorWithRed:17 / 256.f green:27 / 256.f blue:47 / 256.f alpha:1]);
    self.labelForName.dk_backgroundColorPicker = DKColorWithColors([UIColor colorWithRed:232/255.f green:76/255.f blue:84/255.f alpha:1], [UIColor colorWithRed:17 / 256.f green:27 / 256.f blue:47 / 256.f alpha:1]);
    self.labelForName.dk_textColorPicker = DKColorWithColors([UIColor blackColor], [UIColor orangeColor]);
}

- (void)viewWillDisappear:(BOOL)animated {
    [self.player pause];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
